package com.cnu.sys.controller;

import com.cnu.common.Result;
import com.cnu.sys.entity.User;
import com.cnu.sys.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private IUserService userService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @GetMapping("/all")
    public Result<List<User>> getAllUser() {
        List<User> list = userService.list();
        return Result.success(list, "查询成功");
    }

    @PostMapping("/login")
    public Result<Map<String, Object>> login(@RequestBody User user) {
        Map<String, Object> res = userService.login(user);
        if(res != null) {
            return Result.success(res);
        }
        return Result.fail(20002, "用户名或密码错误");
    }

    @GetMapping("/info")
    public Result<Map<String, Object>> getUserInfo(@RequestParam("token") String token){
        Map<String, Object> res = userService.getUserInfo(token);
        if(res != null){
            return Result.success(res);
        }
        return Result.fail(20002, "用户登录失效，请重新登录");
    }

    @PostMapping("/logout")
    public Result<?> logout(@RequestHeader("X-Token") String token){
        userService.logout(token);
        return Result.success();
    }

    @PutMapping("/save/{id}")
    public Result<?> SavePasswordById(@PathVariable("id") Integer id, @RequestBody User user){
        User newUser = userService.getById(id);
        newUser.setPassword(passwordEncoder.encode(user.getPassword()));
        userService.updateById(newUser);
        return Result.success("修改密码成功");
    }
}
